package com.home.base.util;

import org.apache.commons.codec.Charsets;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Http工具类
 */
public class HttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 解析出url参数中的键值对
     * @param url url参数
     * @return 键值对
     */
    public static Map<String, String> getRequestParam(String url) {

        Map<String, String> map = new HashMap<String, String>();
        String[] arrSplit = null;

        // 每个键值为一组
        arrSplit = url.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            // 解析出键值
            if (arrSplitEqual.length > 1) {
                // 正确解析
                map.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    map.put(arrSplitEqual[0], "");
                }
            }
        }
        return map;
    }

    /**
     * 发送POST请求 超时时间5s
     * @param url 请求url
     * @return 结果
     */
    @SuppressWarnings("deprecation")
    public static String doGet(String url, Connection.Method method)  {
        StringBuffer result = new StringBuffer();

        try {
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setSocketTimeout(5000)
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setExpectContinueEnabled(false)
                    .build();
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultRequestConfig(defaultRequestConfig)
                .build();

            HttpGet  request = new HttpGet(url);



        // add request header


        request.addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3659.0 Safari/537.36");
            request.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
            request.addHeader("Content-Type","application/json;charset=utf-8");
            request.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        //    request.addHeader("Host","www.yy.com");
         //   request.addHeader("Connection","keep-alive");
            String host = url.replace("http://", "");
            host = host.substring(0,host.indexOf("/"));
            request.addHeader("host", host);
        HttpResponse response = null;
        response = client.execute(request);
         logger.info("REQUEST ："  + url);
         logger.info("GOT ："  + response.toString() );
         BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8));

        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(
                    line
            );
        }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String rs = result.toString();
//        rs = new String( rs.getBytes(Charset.defaultCharset()), Charsets.UTF_8);
        logger.info("FMT ："  + rs);
        return rs;
    }

}

